package com.chen.project.file_client.controller;

import com.alibaba.fastjson.JSON;
import com.chen.project.file_client.config.FileProps;
import com.chen.project.file_client.pojo.FileInfo;
import com.chen.project.file_client.service.HttpService;
import com.chen.project.file_client.service.impl.HttpServiceImpl;
import com.chen.project.file_client.utils.RSAUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 * @author
 */
@Controller
public class FileInfoController {

    /**
     * RSA 私钥，使用 REAUtils.genKeyPair 生成
     */
    public static final String PRI_KEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIHXQnMLBLgtcyKF8ONoqFkdq00757owJPMRkWnryaIo2i/kyzI1WWo87YkBvy4lvd5kaipZ7yJoRf/GAtYnz64QrPiMUwFOh5OqPHWC0YxECDG0akHrWQNkMvZpVR9d+Kmd3EU50pAX0mKR83VFsrVofQLnhEel+kNL2QjUIQoJAgMBAAECgYB+oqMlrzZwJ6vmnPo/4gBnwl8j2ex9lJ1FEPphc13aMbv0AFMKaiwGSNxnxvNen+LaN9ev7L0mMssq1kZH9tY/C4VQZu8kbvyws63d/RU1unb7tF2dZACeUWT6E6L0TFCujr7daA2Ubm951VFKt96S/cIKAn+ieVWliYZ951KQgQJBAMMD5wfiXutHmmp9uR38oLhG1F+xFxLabOsla/q+67SGWs2Psadkd245yabUsw/xx0E4xSNVV1ORFvl38JKPFhECQQCqccVP2OSPFbq6eFkg4YRM8ORdTQcIrOi8pzzFb7/Yo2kX3S/WjWXkZRZKOVkf1CazGnozX53RT5rz/+0R+dx5AkAjGQm0ho5Uw/9LmTL+7Z+zarQAQOwJLZyauZJ0f3YGeIPRKUJtAQzpnqbnSrKrdPVKjMAWOt7LoHpFDcwTZIMxAkBRqRaWrdy7bPa8tkJFjaacUmGnDeuLzYPoNtvX4DVzLr+ALnnn+nDR31ixkQ5RQIyWDN51VJ9BFDmyI3DKxwJJAkBklBO20UVS0o0JC0z82Ls8sKxqLAC9b4YNKOZiejnsC5t8LVauStyYpPYi4vJPwgk4l4LZ9AhmRPEC56DD0ges";

    /**
     * 文件服务器的相关参数，在配置文件中修改
     */
    @Resource
    private FileProps fileProps;

    @Resource
    private HttpService httpService;

    /**
     * 返回 index 页面
     *
     * @return
     */
    @RequestMapping("/")
    public String index(HttpServletRequest request, Model model) throws Exception {

        String uuid = request.getParameter("uuid");
        String action = request.getParameter("action");

        if (uuid != null) {
            // 通过 uuid 获取元数据json，转换为实体类对象
            String fileInfoJson = httpService.getFileInfoByUuid(uuid);
            FileInfo fileInfo = JSON.parseObject(fileInfoJson, FileInfo.class);

            // 把文件对象存入model
            model.addAttribute("fileInfo", fileInfo);
        } else if ("getFileInfoList".equals(action)) {
            // 获取最近上传的文件的元数据
            String fileInfoListJson = httpService.getFileInfoList();
            List<FileInfo> fileInfoList = JSON.parseArray(fileInfoListJson, FileInfo.class);

            // 把元数据json存入model
            model.addAttribute("fileInfoList", fileInfoList);
        }
        return "index";
    }

    /**
     * 上传文件的请求，接收前端传来的文件，并上传到文件服务器
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model, HttpServletResponse response) throws Exception {

        // 判断文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传失败，没有文件");
        }

        // 上传文件到文件服务器，同时返回文件的 uuid
        String uuid = httpService.upload2Server(file, response);

        // 通过 uuid 获取文件的元数据（json格式），再转化为 FileInfo 对象
        String fileInfoJson = httpService.getFileInfoByUuid(uuid);
        FileInfo fileInfo = JSON.parseObject(fileInfoJson, FileInfo.class);

        // 把文件元数据放到 model 中
        model.addAttribute("fileInfo", fileInfo);

        // 重定向到 / ，返回首页；另外重定向可以防止表单重复提交
        return "redirect:/" + "?uuid=" + uuid;
    }

    /**
     * 下载文件的请求，通过 uuid 从文件服务器下载文件
     *
     * @param uuid     文件的 uuid
     * @param response
     * @throws IOException
     */
    @GetMapping("/download")
    public void download(@RequestParam String uuid, HttpServletResponse response) throws Exception {

        System.out.println("下载请求");
        System.out.println("uuid:" + uuid);

        // 向文件服务器请求文件流，再返回前端
        httpService.downloadFileFromServerByUuid(uuid, response);
    }

    @GetMapping("/fileInfoList")
    public String getFileInfoList() throws Exception {
        return "redirect:/" + "?action=getFileInfoList";
    }

    /**
     * 随机生成请求头 X-SID、X-Signature
     *
     * @return
     * @throws Exception
     */
    private Map<String, String> genHeaders() throws Exception {

        // 生成 X-SID
        String sid = RandomStringUtils.randomAscii(5);

        // 生成 X-Signature
        String signature = RSAUtils.sign(sid.getBytes(), PRI_KEY);

        Map<String, String> map = new HashMap<>(2);
        map.put("X-SID", sid);
        map.put("X-Signature", signature);
        return map;
    }
}
